package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author ZJ
 */
@CanalEventListener  //声明当前的雷士canal的监听类
public class BusinessListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param eventType 当前操作数据库类型  (增删改)
     * @param rowData  当前操作数据库的数据
     */
    @ListenPoint(schema = "changgou_business", table = {"tb_ad"})
    public void adUpdate(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {

        System.out.println("广告数据发生变化");
        System.out.println("eventType:" + eventType.toString());

         /*
        rowData.getBeforeColumnsList().forEach((c)-> System.out.println("改变前的数据："+c.getName()+"::"+c.getValue()));
        System.out.println("========================================");
        rowData.getAfterColumnsList().forEach((c)-> System.out.println("改变后的数据："+c.getName()+"::"+c.getValue()));

        //修改前数据
        for(CanalEntry.Column column: rowData.getBeforeColumnsList()) {
            if(column.getName().equals("position")){
                System.out.println("发送消息到mq:"+column.getValue());
                rabbitTemplate.convertAndSend("",RabbitMQConfig.AD_UPDATE_QUEUE,column.getValue());  //发送消息到mq
                break;
            }
        }
        */

        //1.监听到tb_ad有改动了 rowData
        //2.想mq发消息
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        for (CanalEntry.Column column : afterColumnsList) {
            if(column.getName().equals("position")){
                System.out.println("发送消息到mq"+column.getValue());
                //发送消息到mq
                rabbitTemplate.convertAndSend("", RabbitMQConfig.AD_UPDATE_QUEUE,column.getValue());
            }
        }
    }
}
